package com.caiwangdai.app.origin.list.delegator

import android.support.annotation.NonNull
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.*
import android.view.View
import android.view.ViewGroup
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.Command
import com.caiwangdai.app.backend.observer.OnPageObserver
import com.caiwangdai.app.bean.base.PageB
import com.caiwangdai.app.extension.setTopDrawable
import com.caiwangdai.app.origin.BaseActivity
import com.caiwangdai.app.origin.list.BaseRecyclerAdapter
import com.caiwangdai.app.widget.MultiplyStateViewWM
import com.caiwangdai.app.center.SnakerBarCenter
import kotlinx.android.synthetic.main.content_list_state_empty.view.*
import kotlinx.android.synthetic.main.content_list_state_error.view.*
import kotlinx.android.synthetic.main.content_universal_recyclerview.view.*

/**
 * @project KotLinProject
 * @author 艹羊
 * @date 2017/6/16 下午1:55
 * @description 以recyclerView为主，实现下拉，上拉功能的集成者
 * @remark 1.设置默认下拉
 */
class RecyclerViewDelegator<T> {
    var ITEM_MAX_NUMBER = Integer.MAX_VALUE//设置最大的item数量限制

    //view context
    var mRecyclerView: RecyclerView//列表
    var mRefreshLayout: SwipeRefreshLayout//Google官方下拉控件
    var mFooter: LoadingFooter//上拉显示更多
    var mMultiStateView: MultiplyStateViewWM//多状态视图
    var mContext: BaseActivity


    //paging control
    var mPage: Int = 1
    var mPageSize: Int = 10
    var mAdapter: BaseRecyclerAdapter<T>
    var mCommand: Command<T>? = null

    //custom
    var lastPositions: IntArray? = null
    var lastVisibleItemPosition = 0
    var isSteadyListView = false//是否为固定列表
    var layoutType: LayoutType = LayoutType.LINEAR


    enum class LayoutType {
        LINEAR,
        GRID,
        STAGGERED_GRID
    }

    var onItemClick: ((item: T, position: Int) -> Unit)? = null

    constructor(context: BaseActivity, contentView: ViewGroup, adapter: BaseRecyclerAdapter<T>, command: Command<T>) {
        mContext = context
        mMultiStateView = contentView.multiView
        mRefreshLayout = contentView.swipe_refresh
        mRecyclerView = contentView.recy_universal
        mFooter = LoadingFooter(mContext)
        mAdapter = adapter
        mCommand = command

        initRefreshLayout()
        initRecyclerView()
        initLayoutType()
        setupEmptyView()
        setupErrorView()
    }


    fun initRefreshLayout() {
        mRefreshLayout.setOnRefreshListener {
            beginHeaderRefreshing()
        }
        //下拉刷新控件的配色
        mRefreshLayout.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorPrimary))

    }

    private fun initRecyclerView() {
        //basic recyclerview
        mRecyclerView.layoutManager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
        mRecyclerView.itemAnimator = DefaultItemAnimator() as RecyclerView.ItemAnimator?//设置Item增加、移除动画
        mRecyclerView.adapter = mAdapter

        //scroll
        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                val layoutManager = recyclerView?.layoutManager as RecyclerView.LayoutManager
                val visibleItemCount = layoutManager.childCount
                val totalItemCount = layoutManager.itemCount

                if (visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition == totalItemCount - 1) {
                    if (mAdapter.getDataListCount() >= mPageSize && mFooter.mState != LoadingFooter.State.TheEnd)
                        loadNextPage()
                }
            }

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                //上拉为正 下拉为负
                val layoutManager = getLayoutManager()
                when (layoutType) {
                    LayoutType.LINEAR -> {
                        lastVisibleItemPosition = (layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                    }
                    LayoutType.GRID -> {
                        lastVisibleItemPosition = (layoutManager as GridLayoutManager).findLastVisibleItemPosition()
                    }
                    LayoutType.STAGGERED_GRID -> {
                        val layoutManager = layoutManager as StaggeredGridLayoutManager
                        if (lastPositions == null)
                            lastPositions = IntArray(layoutManager.spanCount)
                        lastVisibleItemPosition = layoutManager.findLastVisibleItemPositions(lastPositions).max()!!
                    }
                }
            }
        })
        //foot  //默认有尾部
        addFooterView(mFooter.mLoadingFooter)
        //item click
        mAdapter.setOnItemClickListener { it ->
            onItemClick?.invoke(mAdapter.getItem(it)!!, it)
        }
    }

    /**
     * 初始化布局类型
     */
    private fun initLayoutType() {
        val layoutManager = getLayoutManager()
        when (layoutManager) {
            is LinearLayoutManager -> layoutType = LayoutType.LINEAR
            is GridLayoutManager -> layoutType = LayoutType.GRID
            is StaggeredGridLayoutManager -> layoutType = LayoutType.STAGGERED_GRID
            else -> {
                throw RuntimeException("Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager")
            }
        }
    }


    fun beginHeaderRefreshing() {
        beginRefreshAnimation()
        loadFirstPage()
    }

    /**
     * 下拉刷新
     */
    fun loadFirstPage() {
        mFooter.setState(LoadingFooter.State.Idle)
        mPage = 1
        mCommand?.execute(mPage.toString(), mPageSize.toString(), object : OnPageObserver<T>(mContext) {
            override fun isShowProgressBar() = false
            override fun onSuccess(value: PageB<T>) {
                endRefreshAnimatioin {}
                //data
                val dataList = value.data?.list as MutableList<T>
                mAdapter.setDataToAdapter(dataList)
                mPage++
                checkReceiveData(dataList)
                checkLocalListData()
                if (mAdapter.itemCount != 0) mRecyclerView.smoothScrollToPosition(0)
            }

            override fun onFail(message: String?) {
                endRefreshAnimatioin { }
                mFooter.setState(LoadingFooter.State.Idle)
                mAdapter.setDataToAdapter(null)
                mMultiStateView.setViewState(MultiplyStateViewWM.VIEW_STATE_ERROR)
            }
        })

    }

    /**
     * 上拉加载更多
     */
    fun loadNextPage() {
        if (isSteadyListView)
            return
        mFooter.setState(LoadingFooter.State.Loading)
        mCommand?.execute(mPage.toString(), mPageSize.toString(), object : OnPageObserver<T>(mContext) {
            override fun isShowProgressBar() = false

            override fun onSuccess(value: PageB<T>) {
                if (mAdapter.getDataListCount() > ITEM_MAX_NUMBER) {
                    mFooter.setState(LoadingFooter.State.TheEnd)
                    return
                }
                //data
                val dataList = value.data?.list
                if (dataList != null && dataList.size > 0) {
                    mPage++
                    mAdapter.addData(dataList)
                    checkReceiveData(dataList, true)
                    checkLocalListData()
                }
            }

            override fun onFail(message: String?) {
                mMultiStateView.setViewState(MultiplyStateViewWM.VIEW_STATE_ERROR)
            }
        })
    }

    /**
     * 检查接收到的数据
     * 如果size小于pageSize则说明没有更多了
     */
    fun checkReceiveData(dataList: List<T>?, isLoadMore: Boolean = false) {
        if (dataList == null) {
            mFooter.setState(LoadingFooter.State.Idle)
            return
        }
        if (dataList.size < mPageSize) {
            mFooter.setState(LoadingFooter.State.TheEnd)
            //如果没有增加尾部
            if (!mAdapter.isAddFoot && isLoadMore) {
                SnakerBarCenter.show(mRecyclerView.parent as ViewGroup, "没有更多了")
            }
        } else {
            mFooter.setState(LoadingFooter.State.Idle)
        }

    }

    /**
     * 检查本地列表的数据
     */
    fun checkLocalListData() {
        if (mAdapter.itemCount == 0)
            mMultiStateView.setViewState(MultiplyStateViewWM.VIEW_STATE_EMPTY)
        else
            mMultiStateView.setViewState(MultiplyStateViewWM.VIEW_STATE_CONTENT)
    }

    /**
     * 获取排序管理者
     */
    fun getLayoutManager(): RecyclerView.LayoutManager {
        return mRecyclerView.layoutManager

    }

    /**
     * 设置排序管理者
     */
    fun setLayoutManager(@NonNull layout: RecyclerView.LayoutManager) {
        mRecyclerView.layoutManager = layout

        //解决GridView加载更多的视图错位问题
        if (layout !is GridLayoutManager) {
            return
        }
        val gridLayoutManager = layout
        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                var spanSize = 1

                if (mAdapter.isAddHead && position == 0) {
                    spanSize = gridLayoutManager.spanCount
                }

                if (mAdapter.isAddFoot && position == mAdapter.getDataListCount()) {
                    spanSize = gridLayoutManager.spanCount
                }
                return spanSize
            }
        }

    }

    /**
     * 增加头部
     */
    fun addHeadView(view: View) {
        mAdapter.addHeadView(view)
    }

    /**
     * 增加ItemDecoration
     */
    fun addItemDecoration(decor: RecyclerView.ItemDecoration) {
        mRecyclerView.addItemDecoration(decor)
    }

    fun beginRefreshAnimation() {
        mRefreshLayout.post {
            mRefreshLayout.isRefreshing = true
        }
    }

    fun endRefreshAnimatioin(f: () -> Unit) {
        mRefreshLayout.postDelayed({
            mRefreshLayout.isRefreshing = false
            f()
        }, 1000)
    }

    //点击事件
    fun setOnItemClickListener(onItemClickListener: (item: T, position: Int) -> Unit) {
        this.onItemClick = onItemClickListener
    }

    /**
     * 变成固定列表
     */
    fun changeToStatedyListView() {
        isSteadyListView = true
        removeFooterView()
        //mRefreshLayout.setEnabled(false);
    }


    open fun setupEmptyView(tips: String = "暂无数据", picRes: Int = -1) {
        val mEmptyView = mMultiStateView.mEmptyView as ViewGroup
        //文字
        mEmptyView.tv_empty.text = tips
        //图片
        if (picRes != -1) {
            mEmptyView.tv_empty.setTopDrawable(picRes)
        }
    }

    open fun setupErrorView(tips: String = "网络异常，请下拉刷新", picRes: Int = -1) {
        val mErrorView = mMultiStateView.mErrorView as ViewGroup
        //文字
        mErrorView.tv_error.text = tips
        //图片
        if (picRes != -1) {
            mErrorView.tv_empty.setTopDrawable(picRes)
        }
    }


    fun addFooterView(view: View) {
        mAdapter.addFootView(view)
    }


    fun removeFooterView() {
        mAdapter.removeFootView()
    }
}